package admin

import (
	"net/http"

	"github.com/labstack/echo/v4"
	"github.com/rs/zerolog/log"
	"gorm.io/gorm"
	"techoiceness.com/aiagent/llm-gateway/internal/entity"
	"techoiceness.com/aiagent/llm-gateway/internal/server/response"
)

// 管理员登录
func (h *AdminHandler) Login(c echo.Context) error {
	var req LoginRequest
	if err := c.Bind(&req); err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, "Invalid request body")
	}

	if err := h.validator.Struct(&req); err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, "Validation failed: "+err.Error())
	}

	// 查找管理员用户
	var admin entity.Admin
	if err := h.db.Where("username = ? AND is_active = ?", req.Username, true).First(&admin).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			return echo.NewHTTPError(http.StatusUnauthorized, "Invalid credentials")
		}
		return echo.NewHTTPError(http.StatusInternalServerError, "Database error")
	}

	// 验证密码
	if !admin.CheckPassword(req.Password) {
		return echo.NewHTTPError(http.StatusUnauthorized, "Invalid credentials")
	}

	// 更新最后登录时间
	admin.UpdateLastLogin()
	h.db.Save(&admin)

	// 生成JWT token
	token, err := h.jwtManager.GenerateToken(admin.ID, admin.Username)
	if err != nil {
		log.Error().
			Str("admin_id", admin.ID.String()).
			Str("admin_username", admin.Username).
			Msg("Failed to generate JWT token for admin login")
		// 记录管理员登录失败日志
		return response.Unauthorized(c, "Failed to generate JWT token")
	}

	// 记录管理员登录成功日志
	log.Info().
		Str("admin_id", admin.ID.String()).
		Str("admin_username", admin.Username).
		Msg("Admin login successful")

	// 安全获取 LastLogin 时间戳，避免 nil pointer
	var lastLogin int64
	if admin.LastLogin != nil {
		lastLogin = admin.LastLogin.Unix()
	}

	return response.Success(c, &LoginResponse{
		ID:        admin.ID,
		Token:     token,
		Username:  admin.Username,
		LastLogin: lastLogin,
		IsActive:  admin.IsActive,
		Role:      string(admin.Role),
		Email:     admin.Email,
	})
}
